package com.ibm.risk.irmp.common.datasource;

import com.zaxxer.hikari.HikariDataSource;
import lombok.Setter;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;

import javax.sql.DataSource;

@Configuration
@ConfigurationProperties(prefix = "spring.datasources")
public class DataSourceConfig {

    @Setter
    private HikariDataSource master;
    @Setter
    private HikariDataSource slave;

    @Bean
    public DataSourceTransactionManager transactionManager(DataSource dataSource,
                                                           ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
        DataSourceTransactionManager transactionManager = new DynaDataSourceTransactionManager(dataSource);
        transactionManagerCustomizers.ifAvailable((customizers) -> customizers.customize((TransactionManager) transactionManager));
        return transactionManager;
    }


    @Bean
    public DataSource createDataSource() {
        DynamicDataSource dds = new DynamicDataSource(master, slave);
        return dds;
    }
}
